<?php

namespace Modules\Asset\Entities;

use Modules\Core\Entities\BaseEntity as Model;
use ThrowException;
use Setting;
use Payment;

class WithdrawRecord extends Model
{
    protected $guarded = [];
    protected $table = 'withdraw_records';
    static public $resourceName = '';

    protected $appends = ['union_status', 'union_status_text', 'auto_pay_status_text'];

    protected $casts = [
        'auto_pay_info' => 'json',
    ];

    public function scopeSearch($query, $key) 
    {
        return $query->whereHas('user', function ($q) use ($key) {
            return $q->where('phone', $key)->orWhere('name', 'like', '%' . $key . '%');
        })->orWhere('account', 'like', '%' . $key . '%')->orWhere('number', $key);;
    }

    // public function getAutoPayStatusAttribute()
    // {
    //     $status = 'unknow';

    //     $map = [
    //         0 => 'none',
    //         1 => 'completed',
    //         2 => 'closed'
    //     ];

    //     return $map[$this->status];
    // }

    public function getAutoPayStatusTextAttribute()
    {
         $map = [
            0 => '无需自动转帐',
            1 => '已成功',
            2 => '需人工审核',
            3 => '已失败',
            4 => '待转帐'
        ];

        return $map[$this->auto_pay_status];
    }


    public function getUnionStatusAttribute()
    {
        $status = 'unknow';

        $map = [
            0 => 'pending',
            1 => 'completed',
            2 => 'closed'
        ];

        return $map[$this->status];
    }

    public function getUnionStatusTextAttribute()
    {
         $map = [
            'pending' => '待处理',
            'completed' => '已成功',
            'closed' => '已取消'
        ];

        return $map[$this->union_status];
    }

    public function scopeType($query, $type)
    {
        return $query->where('asset_type', $type);
    }

    public function scopeStatus($query, $status)
    {
        $statusMap = [
            'pending' => 0,
            'completed' => 1,
            'closed' => 2
        ];
        return $query->where('status', $statusMap[$status]);
    }

    public function user()
    {
        return $this->belongsTo('\Modules\User\Entities\User', 'user_id');
    }

    public function asset()
    {
        return $this->belongsTo('\Modules\Asset\Entities\Asset', 'asset_id');
    }

    static public function generateNumber()
    {
        $number = 'W' . date('dHis') . rand(1000, 9999);
        return $number;
    }

    // 完成
    static public function beforeGetList($options)
    {
        if (@$options['status']) {
            $options['scopes']['status'] = $options['status'];
        }

        return $options;
    }

    // 完成转帐
    public function complete($options)
    {
        if ($this->auto_pay_status !== 0) {
            if ($this->auto_pay_status !== 1) {
               ThrowException::Conflict('自动转帐未完成，请点"立即转帐"或取消此提现');
            }
        }

        if (!$this->asset) {
        	return false;
        }

        $this->asset->cleanFrozen($this->value);

        return $this->update([
            'remark' => @$options['remark'],
            'status' => 1,
            'handled_at' => now()
        ]);
    }

    // 取消转帐
    public function close() 
    {
        $this->asset->unfrozen($this->value);

        return $this->update([
            'status' => 2,
            'auto_pay_status' => 0
        ]);
    }

    // 进行自动转帐
    public function startAutoPay()
    {
        $statusMap = [2, 3, 4];
        if (!in_array($this->auto_pay_status, $statusMap)) {
            ThrowException::Conflict('当前提现记录不可进行自动转帐');
        }

        // 微信零钱
        if ($this->withdraw_type === 'wechat_pay_auto') {
            $options = [
                'number' => $this->number,
                'desc' => '余额提现'
            ];

            // 进行自动转帐
            $res = Payment::EasyWechatPay()->payToUser($this->user, $this->value, $options);

            $this->update([
                'auto_pay_status' => 1,
                'auto_paid_at' => now(),
                'auto_pay_info' => $res
            ]);

            // 标记为已完成
            $this->complete([]);
        }
        else {
            ThrowException::Conflict('未配置的自动转帐方式');
        }
    }
}
